package com.bestillet.kyllingogco;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.AsyncTask.Status;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;

public class MenuActivity extends Activity {
	private ArrayList<ImageTask> tasks;
	private ArrayList<Card> cards;
	private ArrayList<Menu> menu;

	private ShopApplication app;
	private LoadingDialog loading;
	private Category category;
	private MenuTask task;
	
	private Button back, home, basket;
	private ListView list;
	private Context context;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.menu);
		
		tasks = new ArrayList<ImageTask>();
		menu = new ArrayList<Menu>();
		
		context = this;
		
		category = getIntent().getParcelableExtra("category");
		
		app = (ShopApplication) getApplicationContext();
		cards = app.getCards();
		
		list = (ListView) findViewById(android.R.id.list);
		list.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Intent intent = new Intent(context, AddActivity.class);
				intent.putExtra("menu", menu.get(position));
				startActivity(intent);
			}
		});
		
		back = (Button) findViewById(R.id.btnMenuBack);
		back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		home = (Button) findViewById(R.id.btnMenuHome);
		home.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		basket = (Button) findViewById(R.id.btnMenuBasket);
		basket.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(v.getContext(), BasketActivity.class);
				startActivity(intent);
			}
		});
		
		loading = new LoadingDialog(context);
		loading.show();
		
		task = new MenuTask();
		task.execute();
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		
		/*for (Menu m : menu)
			if (m.getImage() != null)
				m.getImage().recycle();*/
		
		if (task != null)
			if (task.getStatus() == Status.RUNNING)
				task.cancel(true);
		
		while (tasks.size() > 0) {
			if (tasks.get(0).getStatus() == Status.RUNNING) {
				tasks.get(0).cancel(true);
				tasks.remove(0);
			}
		}
	}

	@Override
	public boolean onCreateOptionsMenu(android.view.Menu menu) {
		menu.add(android.view.Menu.NONE, -2, 0, "Info");
		menu.add(android.view.Menu.NONE, -1, 0, "Indstillinger");
		menu.add(android.view.Menu.NONE, 0, 0, "Tidligere ordrer");
		for (int i = 0; i < cards.size(); i++)
			menu.add(android.view.Menu.NONE, cards.get(i).getIdx(), cards.get(i).getPosition() + 1, cards.get(i).getName());
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case -2:
			Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://m.kyllingogco.dk/kontakt.asp?shopid=" + app.getShop().getIdx()));
			startActivity(browserIntent);
			break;
		case -1:
			Intent customer = new Intent(this, CustomerActivity.class);
			startActivity(customer);
			break;
		case 0:
			Intent order = new Intent(this, OrderActivity.class);
			startActivity(order);
			break;
		default:
			Intent card = new Intent(this, CardActivity.class);
			card.putExtra("idx", item.getItemId());
			card.putExtra("title", item.getTitle());
			startActivity(card);
			break;
		}
    	return true;
	}
	
	private class MenuTask extends AsyncTask<Void, Void, Boolean> {
    	@Override
		protected Boolean doInBackground(Void... params) {
    		try {
    			InputStream in = Server.post(Server.MENU, Server.getAuthenticationMenu(context, category.getCategoriId()));
    			XmlPullParser parser = Server.toXmlParser(in);
    			menu = XmlParser.getMenu(parser, category.getCategoriId());
    			in.close();
    		} catch (IOException e) {
    			Log.e("Shop", "IOException: " + e.getMessage());
    			return false;
    		} catch (XmlPullParserException e) {
    			Log.e("Shop", "XmlPullParserException: " + e.getMessage());
    			return false;
    		} catch (NullPointerException e) {
    			Log.e("Shop", "NullPointerException: " + e.getMessage());
    			return false;
    		} catch (IllegalArgumentException e) {
    			Log.e("Shop", "IllegalArgumentException: " + e.getMessage());
    			return false;
    		}
    		return true;
    	}
    
	    @Override
	    protected void onPostExecute(Boolean success) {
	    	if (success) {
    			for (int i = 0; i < menu.size(); i++) {
    				Bitmap b = app.getBitmapFromMemCache(menu.get(i).getPicturenormal());
    				if (b != null) {
    					if (b.isRecycled()) {
    						app.removeBitmapFromMemoryCache(menu.get(i).getPicturenormal());
    	    				ImageTask it = new ImageTask();
    	    				it.execute(i);
    	    				tasks.add(it);
    					} else {
        					menu.get(i).setImage(b);
    					}
    				} else {
	    				ImageTask it = new ImageTask();
	    				it.execute(i);
	    				tasks.add(it);
    				}
    			}

    			MenuArrayAdapter adapter = new MenuArrayAdapter(context, menu);
    			list.setAdapter(adapter);
	    	} else {
	    		AlertDialog.Builder builder = new AlertDialog.Builder(context);
	    		builder.setMessage(R.string.error_menus)
	    		       .setTitle(R.string.error)
	    		       .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								task = new MenuTask();
								task.execute();
								loading.show();
							}
						})
						.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								finish();
							}
						});
	    		AlertDialog dialog = builder.create();
	    		dialog.show();
	    	}
    		loading.dismiss();
	    }
	}
	
	private class ImageTask extends AsyncTask<Integer, Void, Boolean> {
		private Bitmap b;
		private int index;
		
    	@Override
		protected Boolean doInBackground(Integer... params) {
    		try {
    			index = params[0];
    			Menu m = menu.get(index);
    			InputStream in = Server.get(Server.PRODUCT_IMAGES + m.getPicturenormal());
    			b = Server.downloadBitmap(in, (Activity)context);
    			in.close();
    			m.setImage(b);
    			app.addBitmapToMemoryCache(m.getPicturenormal(), b);
			} catch (IOException e) {
    			Log.e("Shop", "IOException: " + e.getMessage());
				return false;
			} catch (NullPointerException e) {
    			Log.e("Shop", "NullPointerException: " + e.getMessage());
				return false;
			} catch (OutOfMemoryError e) {
    			Log.e("Shop", "OutOfMemoryError: " + e.getMessage());
				return false;
			}
    		return true;
    	}
    
	    @Override
	    protected void onPostExecute(Boolean success) {
	    	if (success) {
    			runOnUiThread(new Runnable() {
    				@Override
    				public void run() {
    					try {
	    	    			View v = list.getChildAt(index);
	    	    			ImageView image = (ImageView) v.findViewById(R.id.imgImage);
	    	    			image.setImageBitmap(b);
    					} catch (NullPointerException e) { }
    				}
    			});
	    	}
			tasks.remove(this);
	    }
	}
}